import { message, Drawer, FormInstance, Image, Tag, Modal, Button } from 'antd';
import React, { useState, useRef, useEffect } from 'react';
import { PageContainer } from '@ant-design/pro-layout';
import type { ProColumns, ActionType } from '@ant-design/pro-table';
import ProTable from '@ant-design/pro-table';
import {
  ModalForm,
  ProFormText,
  ProFormDependency,
  DrawerForm,
  ProFormDatePicker,
} from '@ant-design/pro-form';
import ProDescriptions, { ProDescriptionsItemProps } from '@ant-design/pro-descriptions';
import {
  dataList,
  loadData,
  loadSelectTag,
  employeeList,
  updatePostpone,
  loadTaskData,
  loadTaskQualification,
  loadRecordData,
  // orgDataList,
} from './service';
import type { PlanBody, PlanListItem, PlanListPagination } from './data';

import { EmployeeListItem } from '@/pages/Employee/List/data';
import moment, { Moment } from 'moment';
import 'moment/locale/zh-cn';
import { request } from 'umi';
import CheckModule from '@/components/CheckModule';
import { PlanRecordListItem } from './data';

const handleSavePostpone = async (fields: PlanBody) => {
  const hide = message.loading('正在保存');

  try {
    await updatePostpone({ ...fields });
    hide();
    message.success('保存成功');
    return true;
  } catch (error) {
    hide();
    message.error('保存失败请重试');
    return false;
  }
};
const requestTag = async () => {
  return loadSelectTag().then(({ data }) => {
    return data;
  });
};
const TrainTaskPage: React.FC = (props) => {
  // @ts-ignore
  const { location, match } = props; // 在构造函数 constructor(props) 中获取时 直接是 props
  const [category, setCategory] = useState<number>(0);

  useEffect(() => {
    if (location.pathname == '/train/statistic/post') {
      setCategory(1);
    }
  }, []);

  const [employeeModalVisible, handleEmployeeModalVisible] = useState<boolean>(false);
  const [postponeModalVisible, handlePostponeModalVisible] = useState<boolean>(false);
  const [recordModalVisible, handleRecordModalVisible] = useState<boolean>(false);
  const [qualificationModalVisible, handleQualificationModalVisible] = useState<boolean>(false);
  const [showDetail, setShowDetail] = useState<boolean>(false);
  const actionRef = useRef<ActionType>();
  const actionEmployeeRef = useRef<ActionType>();
  const actionRecordRef = useRef<ActionType>();
  const formCoursewareRef = useRef<FormInstance>();
  const formRecordRef = useRef<FormInstance>();
  const [currentRow, setCurrentRow] = useState<PlanListItem>();
  const [currentEmployeeRow, setCurrentEmployeeRow] = useState<EmployeeListItem>();
  const columns: ProColumns<PlanListItem>[] = [
    {
      title: '序号',
      dataIndex: 'index',
      valueType: 'indexBorder',
      render: (dom, entity, index) => {
        return (
          <span>
            {index +
              1 +
              ((actionRef?.current?.pageInfo?.current || 1) - 1) *
                (actionRef?.current?.pageInfo?.pageSize || 5)}
          </span>
        );
      },
    },
    {
      title: '计划名称',
      dataIndex: 'name',
    },
    {
      title: '是否考试',
      dataIndex: 'exam',
      search: false,
      hideInTable: true,
      valueEnum: {
        0: {
          text: '不考试',
          status: 'Default',
        },
        1: {
          text: '考试',
          status: 'Success',
        },
      },
    },

    {
      title: '状态',
      dataIndex: 'publish',
      hideInTable: true,
      search: false,
      initialValue: 1,
      valueEnum: {
        0: {
          text: '未发布',
          status: 'Error',
        },
        1: {
          text: '已发布',
          status: 'Success',
        },
      },
    },
    {
      title: '标签',
      search: false,
      dataIndex: 'tags',
      request: requestTag,
      render: (_, record) => (
        <>
          {record?.tagNames?.map((name, index) => (
            <Tag key={name + index + record.planId}>{name}</Tag>
          ))}
        </>
      ),
    },
    {
      search: false,
      title: '培训时间',
      dataIndex: 'startTime',
      render: (_, record) => {
        if (category == 1) {
          return <>{record.startTime}</>;
        } else {
          return (
            <>
              {record.startTime} 至 {record.endTime}
            </>
          );
        }
      },
    },

    {
      title: '学员人数',
      dataIndex: 'employeeNum',
      search: false,
    },
    {
      title: '通过学员人数',
      dataIndex: 'completeNum',
      search: false,
    },
    {
      title: '完成率',
      dataIndex: 'passRate',
      search: false,
      // @ts-ignore
      render: (_, record) => (
        <>
          {(
            (parseFloat((record?.completeNum ?? '0').toString()) /
              ((record?.employeeNum ?? 1) == 0 ? 1 : record?.employeeNum ?? 1)) *
            100
          ).toFixed(2)}
          %
        </>
      ),
    },
    {
      title: '创建时间',
      sorter: true,
      hideInTable: true,
      hideInDescriptions: true,
      dataIndex: 'updateTime',
      valueType: 'dateTime',
      search: false,
    },
    {
      title: '更新时间',
      sorter: true,
      hideInDescriptions: true,
      hideInTable: true,
      dataIndex: 'updateTime',
      valueType: 'dateTime',
      search: false,
    },
    {
      title: '操作',
      dataIndex: 'option',
      valueType: 'option',
      hideInDescriptions: true,
      render: (_, record) => {
        return [
          <a
            key="employee"
            onClick={() => {
              // message.info('开发中');
              setCurrentRow(record);
              handleEmployeeModalVisible(true);
            }}
          >
            详情
          </a>,
        ];
      },
    },
  ];
  // const orgColumns: ProColumns<PlanListItem>[] = [
  //   {
  //     title: '序号',
  //     dataIndex: 'index',
  //     width: 48,
  //     align: 'center',
  //     valueType: 'indexBorder',
  //     render: (dom, entity, index) => {
  //       return (
  //         <span>
  //           {index +
  //             1 +
  //             ((actionRef?.current?.pageInfo?.current || 1) - 1) *
  //             (actionRef?.current?.pageInfo?.pageSize || 5)}
  //         </span>
  //       );
  //     },
  //   },
  //   {
  //     title: '名称',
  //     dataIndex: 'name',
  //   },
  //   {
  //     title: '学员人数',
  //     dataIndex: 'employeeNum',
  //     align: 'center',
  //   },
  //   {
  //     title: '通过学员人数',
  //     dataIndex: 'completeNum',
  //     align: 'center',
  //   },
  //   {
  //     title: '完成率',
  //     dataIndex: 'completeRate',
  //     align: 'center',
  //   },
  //   // {
  //   //   title: '操作',
  //   //   dataIndex: 'option',
  //   //   valueType: 'option',
  //   //   hideInDescriptions: true,
  //   //   render: (_, record) => {
  //   //     return [
  //   //       <a
  //   //         key="employee"
  //   //         onClick={() => {
  //   //           setCurrentRow(record);
  //   //           handleEmployeeModalVisible(true);
  //   //         }}
  //   //       >
  //   //         任务管理
  //   //       </a>,
  //   //
  //   //     ];
  //   //   },
  //   // },
  // ];

  const employeeColumns: ProColumns<EmployeeListItem>[] = [
    {
      dataIndex: 'index',
      width: 48,
      align: 'center',
      valueType: 'index',
      render: (dom, entity, index) => {
        return (
          <span>
            {index +
              1 +
              ((actionEmployeeRef?.current?.pageInfo?.current || 1) - 1) *
                (actionEmployeeRef?.current?.pageInfo?.pageSize || 5)}
          </span>
        );
      },
    },
    {
      title: '员工姓名',
      key: 'name',
      dataIndex: 'name',
    },
    // {
    //   title: '手机号',
    //   key: 'mobile',
    //   dataIndex: 'mobile',
    // },
    // {
    //   title: '身份证号',
    //   key: 'idCard',
    //   dataIndex: 'idCard',
    // },
    {
      title: '开始时间',
      key: 'startTime',
      dataIndex: 'startTime',
    },
    {
      title: '结束时间',
      key: 'endTime',
      dataIndex: 'endTime',
    },
    {
      title: '是否学习',
      dataIndex: 'study',
      valueEnum: {
        0: {
          text: '未学习',
          status: 'Default',
        },
        1: {
          text: '已学习',
          status: 'Success',
        },
      },
    },
    {
      title: '是否考试',
      dataIndex: 'exam',
      valueEnum: {
        0: {
          text: '未考试',
          status: 'Default',
        },
        1: {
          text: '已考试',
          status: 'Success',
        },
      },
    },
    {
      title: '操作',
      dataIndex: 'option',
      valueType: 'option',
      hideInDescriptions: true,
      render: (_, record) => {
        return [
          // <a
          //   key="view"
          //   onClick={() => {
          //     // formRef.current?.resetFields();
          //     // setCurrentRow(record);
          //     // setShowDetail(true);
          //   }}
          // >
          //   查看
          // </a>,
          <a
            key="employee"
            onClick={() => {
              setCurrentEmployeeRow(record);
              handlePostponeModalVisible(true);
            }}
          >
            延期
          </a>,
          <a
            key="prove"
            onClick={() => {
              // if (!record.qualification) {
              //   message.error('未找到合格证明或者培训未学习完成！');
              // } else {
              setCurrentEmployeeRow(record);
              handleQualificationModalVisible(true);
              // }
            }}
          >
            证明
          </a>,
          <a
            key="study"
            onClick={() => {
              setCurrentEmployeeRow(record);
              handleRecordModalVisible(true);
              console.log('ddddddddd', recordModalVisible);
            }}
          >
            记录
          </a>,
        ];
      },
    },
  ];
  const recordColumns: ProColumns<PlanRecordListItem>[] = [
    {
      dataIndex: 'index',
      width: 48,
      align: 'center',
      valueType: 'index',
      render: (dom, entity, index) => {
        return (
          <span>
            {index +
              1 +
              ((actionEmployeeRef?.current?.pageInfo?.current || 1) - 1) *
                (actionEmployeeRef?.current?.pageInfo?.pageSize || 5)}
          </span>
        );
      },
    },
    {
      title: '课件名称',
      key: 'coursewareName',
      dataIndex: 'coursewareName',
      ellipsis: true,
    },
    {
      title: '开始时间',
      key: 'startTime',
      dataIndex: 'startTime',
    },
    {
      title: '结束时间',
      key: 'endTime',
      dataIndex: 'endTime',
    },
  ];
  const [previewData, setPreviewData] = useState({
    visible: false,
    image: '',
    title: '',
  });

  const disabledDate = (current: Moment) => {
    return current && current < moment().subtract(1, 'days').endOf('day');
  };
  // if (location.pathname == '/train/statistic/post') {
  //   setCateogry(1);
  // }
  return (
    <CheckModule code={'TR'}>
      <PageContainer
        waterMarkProps={{ content: '' }}
        onTabChange={(k) => {
          setCategory(parseInt(k));
        }}
        tabActiveKey={category.toString()}
        tabList={[
          {
            tab: '安全培训',
            key: '0',
          },
          {
            tab: '岗前培训',
            key: '1',
          },
          {
            tab: '四新培训',
            key: '2',
          },
          {
            tab: '技能培训',
            key: '3',
          },
          {
            tab: '其它培训',
            key: '99',
          },
        ]}
      >
        <ProTable<PlanListItem, PlanListPagination>
          headerTitle="计划列表"
          actionRef={actionRef}
          rowKey="planId"
          search={{
            labelWidth: 120,
          }}
          options={false}
          request={dataList}
          columns={columns}
          // @ts-ignore
          params={{ category }}
        />

        <DrawerForm<PlanBody>
          title={'任务管理'}
          formRef={formCoursewareRef}
          layout={'horizontal'}
          labelCol={{ span: 4 }}
          width={'80%'}
          wrapperCol={{ span: 18 }}
          visible={employeeModalVisible}
          onVisibleChange={(visible) => {
            if (!visible) {
              setCurrentRow(undefined);
            }
            handleEmployeeModalVisible(visible);
          }}
          drawerProps={{
            destroyOnClose: true,
            maskClosable: false,
            bodyStyle: {
              // paddingTop: 0,
            },
          }}
          submitter={{
            searchConfig: {
              submitText: '保存',
              resetText: '关闭',
            },
            submitButtonProps: {
              style: {
                display: 'none',
              },
            },
          }}
          onFinish={async (value) => {
            handleEmployeeModalVisible(false);
          }}
          // @ts-ignore
          request={(params: PlanBody) => {
            console.log(params);
            if (params.planId) {
              return loadData(params).then(({ data }) => {
                data.dateRange = [data.startTime ?? '', data.endTime ?? ''];
                data.startTime = data.startTime + ' 00:00:00';
                data.endTime = data.endTime + ' 00:00:00';
                if (data.tags) data.tagList = data.tags;
                return data;
              });
            }
          }}
          params={{ ...currentRow }}
        >
          {currentRow?.planId && (
            <ProDescriptions<PlanBody>
              column={2}
              bordered={true}
              title={'计划详情'}
              // @ts-ignore
              request={loadData}
              // layout={'vertical'}
              params={currentRow}
              columns={columns as ProDescriptionsItemProps<PlanBody>[]}
            />
          )}
          {/*<ProTable<PlanListItem, PlanListPagination>*/}
          {/*  headerTitle="情况汇总"*/}
          {/*  rowKey="orgId"*/}
          {/*  tooltip={'跨部门人员会重复统计'}*/}
          {/*  cardProps={{*/}
          {/*    bodyStyle: {padding: 0},*/}
          {/*  }}*/}
          {/*  size={'small'}*/}
          {/*  options={{*/}
          {/*    density: false,*/}
          {/*    setting: false,*/}
          {/*    search: false,*/}
          {/*  }}*/}
          {/*  pagination={false}*/}
          {/*  columns={orgColumns}*/}
          {/*  bordered*/}
          {/*  search={false}*/}
          {/*  // @ts-ignore*/}
          {/*  request={orgDataList}*/}
          {/*  // @ts-ignore*/}
          {/*  params={{planId: currentRow?.planId ?? 0}}*/}
          {/*/>*/}

          <ProTable<EmployeeListItem>
            headerTitle="学员列表"
            size={'small'}
            cardProps={{
              bodyStyle: { padding: 0 },
            }}
            scroll={{ y: 500 }}
            // dataSource={selectCourseware}
            request={async () => {
              let newVar = await employeeList(currentRow?.planId ?? 0);
              console.log(newVar);
              return {
                data: newVar.data,
                // success 请返回 true，
                // 不然 table 会停止解析数据，即使有数据
                success: true,
                // 不传会使用 data 的长度，如果是分页一定要传
                total: newVar.data.length,
              };
            }}
            rowKey="employeeId"
            bordered
            options={{
              density: false,
              setting: false,
              search: false,
            }}
            pagination={false}
            actionRef={actionEmployeeRef}
            columns={employeeColumns}
            search={false}
            dateFormatter="string"
          />
        </DrawerForm>
        <ModalForm<PlanBody>
          title={'培训延期'}
          formRef={formCoursewareRef}
          layout={'horizontal'}
          labelCol={{ span: 4 }}
          wrapperCol={{ span: 18 }}
          visible={postponeModalVisible}
          onVisibleChange={(visible) => {
            if (!visible) {
              setCurrentEmployeeRow(undefined);
            }
            handlePostponeModalVisible(visible);
          }}
          modalProps={{ destroyOnClose: true, maskClosable: false }}
          onFinish={async (value) => {
            value.date = value.endTime;
            const success = await handleSavePostpone(value);
            if (success) {
              handlePostponeModalVisible(false);
              // @ts-ignore
              actionRef?.current?.reloadAndRest();
              actionEmployeeRef?.current?.reload();
            }
          }}
          // @ts-ignore
          request={(params) => {
            console.log(params, 111111111);
            if (params.taskId) {
              return loadTaskData(params as PlanBody).then(({ data }) => {
                data.taskId = data.id;
                return data;
              });
            }
          }}
          params={{ ...currentEmployeeRow }}
        >
          <ProFormText hidden name="planId" />
          <ProFormText hidden name="taskId" />
          <ProFormDatePicker
            rules={[{ required: true }]}
            name="endTime"
            label="结束时间"
            fieldProps={{ disabledDate }}
          />
          {/*<ProForm.Item label={"学员列表"}>*/}
        </ModalForm>
        <Modal
          visible={recordModalVisible}
          title={'学习记录'}
          width={'800px'}
          destroyOnClose={true}
          maskClosable={false}
          // footer={null}
          footer={[
            <Button
              key="back"
              onClick={() => {
                handleRecordModalVisible(false);
              }}
            >
              关闭
            </Button>,
          ]}
          onCancel={() => {
            handleRecordModalVisible(false);
          }}
        >
          <ProTable<PlanRecordListItem>
            headerTitle="学习记录"
            size={'small'}
            cardProps={{
              bodyStyle: { padding: 0 },
            }}
            // dataSource={selectCourseware}
            request={async () => {
              let newVar = await loadRecordData(currentEmployeeRow);
              console.log(newVar);
              return {
                data: newVar.data,
                // success 请返回 true，
                // 不然 table 会停止解析数据，即使有数据
                success: true,
                // 不传会使用 data 的长度，如果是分页一定要传
                total: newVar.data.length,
              };
            }}
            rowKey="id"
            bordered
            options={{
              density: false,
              setting: false,
              search: false,
            }}
            pagination={false}
            actionRef={actionRecordRef}
            columns={recordColumns}
            search={false}
            dateFormatter="string"
          />
        </Modal>

        <ModalForm
          title={'培训证明'}
          formRef={formCoursewareRef}
          layout={'horizontal'}
          labelCol={{ span: 4 }}
          wrapperCol={{ span: 18 }}
          visible={qualificationModalVisible}
          onVisibleChange={(visible) => {
            if (!visible) {
              setCurrentEmployeeRow(undefined);
            }
            handleQualificationModalVisible(visible);
          }}
          submitter={{
            searchConfig: {
              submitText: '下载',
              resetText: '关闭',
            },
          }}
          modalProps={{ destroyOnClose: true, maskClosable: false }}
          // @ts-ignore
          onFinish={(formData) => {
            request(formData.qualification, {
              method: 'GET',
              // 必须加responseType: 'blob',
              responseType: 'blob',
            }).then((res) => {
              const blob = new Blob([res]); //注意拿到的是数据流！！
              const objectURL = URL.createObjectURL(blob);
              let btn = document.createElement('a');
              btn.download = '培训合格证明.jpg'; //文件类型
              btn.href = objectURL;
              btn.click();
              URL.revokeObjectURL(objectURL);
              // @ts-ignore
              btn = null;
            });
          }}
          // @ts-ignore
          request={(params) => {
            console.log(params, 111111111);
            if (params.taskId) {
              return loadTaskQualification(params as PlanBody).then(({ data }) => {
                data.taskId = data.id;
                return data;
              });
            }
          }}
          params={{ ...currentEmployeeRow }}
        >
          <ProFormText hidden name="planId" />
          <ProFormText hidden name="taskId" />
          <ProFormText hidden name="qualification" />
          <ProFormDependency name={['qualification']}>
            {({ qualification }) => {
              return <Image id={'prints-qualification'} src={qualification} />;
            }}
          </ProFormDependency>
        </ModalForm>
        <Image
          width={200}
          style={{ display: 'none' }}
          src={previewData.image}
          preview={{
            visible: previewData.visible,
            src: previewData.image,
            onVisibleChange: (value) => {
              setPreviewData({ image: previewData.image, title: '', visible: value });
            },
          }}
        />
        <Drawer
          width={800}
          visible={showDetail}
          onClose={() => {
            setCurrentRow(undefined);
            setShowDetail(false);
          }}
          closable={false}
        >
          {currentRow?.planId && (
            <ProDescriptions<PlanBody>
              column={1}
              bordered={true}
              title={'计划详情'}
              // @ts-ignore
              request={loadData}
              // layout={'vertical'}
              params={currentRow}
              columns={columns as ProDescriptionsItemProps<PlanBody>[]}
            />
          )}
        </Drawer>
      </PageContainer>
    </CheckModule>
  );
};

export default TrainTaskPage;
